<?php 

namespace app\api\controller;

use think\Controller;
use think\Db;
use think\Request;

class Chat extends Controller{
	// 文本消息持久化
	public function save_message(){
		if(Request::instance()->isAjax()){
			$message = input("post.");
			$datas['fromid']=$message['fromid'];
			$datas['fromname']=$this->getName($datas['fromid']);
			$datas['toid']=$message['toid'];
			$datas['toname']=$this->getName($datas['toid']);
			$datas['content']=$message['data'];
			// $datas['isread']=$message['isread'];
			$datas['isread']=0;   // 先全为未读，当用户进入聊天页面时全部更新为已读
			$datas['type']=1;
			$datas['time']=time();

			Db::table('content')->insert($datas);
		}
	}

	// 根据用户id返回用户姓名
	public function getName($uid){
		$userinfo = Db::table('user')->where('id',$uid)->field('nickname')->find();
		return $userinfo['nickname'];
	}

	// 根据用户id获取聊天双方头像信息
	public function get_head(){
		if(Request::instance()->isAjax()){
			$fromid = input('fromid');
			$toid = input('toid');
			$frominfo = Db::table('user')->where('id',$fromid)->field('headimgurl')->find();
			$toinfo = Db::table('user')->where('id',$toid)->field('headimgurl')->find();
			return [
				'from_head'=>$frominfo['headimgurl'],
				'to_head'=>$toinfo['headimgurl']
			];
		}
	}

	// 获取聊天对象的昵称
	public function get_name(){
		if(Request::instance()->isAjax()){
			$uid = input('toid');
			$toinfo = Db::table('user')->where('id',$uid)->field('nickname')->find();
			return ['toname'=>$toinfo['nickname']];
		}
	}

	// 页面加载 获取两者聊天记录
	public function load(){
		if(Request::instance()->isAjax()){
			$fromid = input('fromid');
			$toid = input('toid');
			
			$count = Db::table('content')->where('(fromid=:fromid and toid=:toid) || (fromid=:toid1 and toid=:fromid1)',['fromid'=>$fromid,'toid'=>$toid,'toid1'=>$toid,'fromid1'=>$fromid])->count('id');
			if($count>=10){
				$message = Db::table('content')->where('(fromid=:fromid and toid=:toid) || (fromid=:toid1 and toid=:fromid1)',['fromid'=>$fromid,'toid'=>$toid,'toid1'=>$toid,'fromid1'=>$fromid])->limit($count-10,10)->order('id')->select();
			}else{
				$message = Db::table('content')->where('(fromid=:fromid and toid=:toid) || (fromid=:toid1 and toid=:fromid1)',['fromid'=>$fromid,'toid'=>$toid,'toid1'=>$toid,'fromid1'=>$fromid])->order('id')->select();
			}
			return $message;
		}
	}

	// 上传图片，返回图片地址
	public function uploading(){
		$file = $_FILES['file'];
		$fromid = input('fromid');
		$toid = input('toid');
		$online = input('online');

		$suffix = strtolower(strrchr($file['name'], '.'));  //获取到上传图片格式，转小写
		$type = ['.jpg','.jpeg','.gif','.png'];
		if(!in_array($suffix,$type)){
			return ['status'=>'图片格式有误'];
		}

		if($file['size']/1024>5120){
			return ['status'=>'图片太大'];
		}

		$filename = uniqid("chat_img_",false);  //生成图片名字
		$uploadpath = ROOT_PATH.'public\\uploads\\chat\\';
		$file_up = $uploadpath.$filename.$suffix;
		// var_dump($file);
		// var_dump($uploadpath);
		$re = move_uploaded_file($file['tmp_name'], $file_up);  //将上传的图片移动到自己指定位置
		
		if($re){
			$name = $filename.$suffix;
			$data['content'] = $name;
			$data['fromid'] = $fromid;
			$data['toid'] = $toid;
			$data['fromname'] = $this->getName($data['fromid']);
			$data['toname'] = $this->getName($data['toid']);
			$data['time'] = time();
			// $data['isread'] = $online;
			$data['isread']=0;  // 先全为未读，当用户进入聊天页面时全部更新为已读
			$data['type'] = 2;   //代表图片
			$message_id = Db::table('content')->insertGetId($data);
			if($message_id){
				
				return ['status'=>'ok','img_name'=>$name];
			}else{
				return ['status'=>'上传出现错误'];
			}
		}

	}

	// 进入聊天页面后 将两者消息全部标为已读
	public function changeNoRead(){
		if(Request::instance()->isAjax()){
			$fromid = input('toid');
			$toid = input('fromid');
			Db::table('content')->where(['fromid'=>$fromid,'toid'=>$toid])->update(['isread'=>1]);
		}
	}


	/**
	 * list页面的方法
	 * 根据fromid来获取用户聊天列表
	 * 
	 */
	public function get_list(){
		if(Request::instance()->isAjax()){
			$fromid = input('id');
			// 获取和fromid聊天的用户列表
			$info = Db::table('content')->where('toid',$fromid)->field('fromid,toid,fromname')->group('fromid')->select();

			$rows = array_map(function($res){
				return [
					'head_url'=>$this->get_head_one($res['fromid']),  //获取对话头像
					'username'=>$res['fromname'],
					'countNoread'=>$this->getCountNoread($res['fromid'],$res['toid']),  //未读消息数量
					'last_message'=>$this->getLastMessage($res['fromid'],$res['toid']),  //最后一条消息和时间
					'chat_page'=>"http://chat.admin/index.php/index/index/index?fromid={$res['toid']}&&toid={$res['fromid']}",  //点击与用户聊天页面
				];
			},$info);
			return $rows;
		}
	}

	// 根据uid获取它的头像
	public function get_head_one($uid){
		$fromhead = Db::table('user')->where('id',$uid)->field('headimgurl')->find();
		return $fromhead['headimgurl'];
	}
	// 获取对话用户之间未读消息
	public function getCountNoread($fromid,$toid){
		return Db::table('content')->where(['fromid'=>$fromid,'toid'=>$toid,'isread'=>0])->count();
	}
	// 获取对话用户最后一条消息和时间
	public function getLastMessage($fromid,$toid){
		$info = Db::table('content')->where('(fromid=:fromid&&toid=:toid)||(fromid=:fromid2&&toid=:toid2)',['fromid'=>$fromid,'toid'=>$toid,'fromid2'=>$toid,'toid2'=>$fromid])->order('id DESC')->limit(1)->find();
		return $info;
	}

}

 ?>